package com.kdtech.analyse.news;
import com.kdtech.analyse.AnalyseNews;
import com.kdtech.utils.HtmlCleaner;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.kdtech.crawler.CrawlHTML;
import com.kdtech.entity.crawler.UrlMeta;
import com.kdtech.entity.data.NewsMeta;
import com.kdtech.utils.DateUtils;
import com.kdtech.utils.HtmlCleaner;
import com.kdtech.utils.StringUtils;
import com.kdtech.utils.HtmlCleaner;

/**
 * 中国国家地理网
 * @author Persh
 *
 */
public class Dili360NewsAnalyse implements AnalyseNews {

	private static final String[] regex={
		"http://[a-z]*.dili360.com/.*/[0-9]{4}/[0-9]*.shtml",
		"http://bbs.dili360.com/thread-[0-9]+-[0-9]+-[0-9]+.html"
		//http://bbs.dili360.com/thread-1167296-1-1.html
	};


	
	public boolean isDetailPage(String url) {
		for (int i=0; i < regex.length; i++) {
			if (url.matches(regex[i])) {
				return true;
			}
		}
		return false;
	}

	
	public NewsMeta parserHtml(UrlMeta urlMeta) {
		NewsMeta news=new NewsMeta();
		String htmltxt=urlMeta.getHtml();
		String url=urlMeta.getUrl();

		news.setUrl(url);
		String title=null;
		String content=null;
		String author=null;
		Long date=null;
		Document doc=Jsoup.parse(htmltxt);
		title =doc.select("#content h2").text();
		if(StringUtils.isBlank(title)){
			title =doc.select("span#thread_subject").text();
		}
		content=HtmlCleaner.getContentHtml(url,doc.select("div#artibody"));
		if(StringUtils.isBlank(content)){
			content=HtmlCleaner.getContentHtml(url,doc.select("div.t_fsz"));
		}

		/*
		 * 作者
		 */
		String authorStr=null;
		authorStr=doc.select("div.date a").text();
		author=authorStr;

		date=DateUtils.matchDate(doc.select("div.date").text());
		if(date==null){
			date=DateUtils.matchDate(doc.select("em#authorposton3227327").text());
		}

		news.setTitle(StringUtils.trimSpace(title));
		news.setContent(content);
		news.setAuthor(author);
		news.setDate(date);

		return news;
	}

	public static void main(String[] args) {
		Dili360NewsAnalyse analyse=new Dili360NewsAnalyse();
		String url="http://bbs.dili360.com/thread-1167296-1-1.html";
		UrlMeta meta=CrawlHTML.responseToURL(url);
		System.out.println(analyse.parserHtml(meta));
	}

	
	public NewsMeta Update(NewsMeta meta) {
		return null;
	}

	
	public boolean isNeedUpdate(){
		return false;
	}
}
